const app = getApp();
const _requsetCYZ = require('../../utils/requestData');
const _functionCYZ = require('../../utils/common.js');
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');// 引入SDK核心类
Page({
	data: {
		this_huodong_qiandao_open:0,
		this_huodong_share_open: 0,
		this_huodong_data:null,
		app_tongji_data:null,
		this_login_user_id:0,
		this_config_op:null,
		this_app_muchcity_open: false,
		this_app_muchcity_select: 2,
		this_app_title: '同城信息',
		sdk_user_address_info: [],
		this_c_config: null,
		this_s_keywords: '',
		select_type: 0,
		this_u_lat: 0,
		this_u_lng: 0,
		this_user_city: '全国',
		this_ad_list_data: null,
		this_huodong_list: null,
		this_cate_list_data: null,
		this_info_list_data: null,
		this_one_ad_data:null,
		this_gonggao_data:null,
		commentParam: [],
		this_page_size: 1,
		this_page_num: 10,
		is_loadmore: true,
		this_user_select_city: '',
		select_city_layer_status: false,
		this_config_commnet_show: false,
		this_show_juli: false,
		is_dots: true,
		swiper_data_num: 5,
		swiperCurrent: 0,
		is_hongbao_open:0,
		index_isshow_add:0,//是否显示首页发布按钮
		info_index_iconnum:5,//首页图标横排个数
		is_show_huodong: false,
		is_show_service: false,//是否显示客服聊天
		this_service_config: null,
		index_share_title:'',
		index_share_img:''
	},
	pushFormSubmit:function(e){
		console.log(e);
	},
	//显示活动
	show_huodong_bind: function () {
		this.setData({ is_show_huodong: this.data.is_show_huodong ? false : true });
	},
	select_city_bind: function (e) {
		var that = this;
		var this_c_name = e.currentTarget.dataset.name;
		var this_c_field = e.currentTarget.dataset.field;
		that.setData({ this_city_field: this_c_field, this_user_select_city: this_c_name });
		that.setData({ this_city_parent_level: e.currentTarget.id });
		_functionCYZ.CYZ_loading();
		var requestData = {};
		requestData.parent_level = that.data.this_city_parent_level;
		_requsetCYZ.cyz_requestGet('/Index/getCityList', requestData, function (xyz_data) {
			wx.hideToast();
			if (xyz_data.info == null) {
				that.set_alert_content_confrim();
				return false;
			}
			that.setData({ this_city_data: xyz_data.info, select_city_layer_status: true });
		});
	},
	set_alert_content_setno: function () {
		var that = this;
		this.set_alert_content_close();
	},
	//关闭城市
	set_alert_content_close: function () {
		this.setData({ this_city_data: [], select_city_layer_status: false, this_city_parent_level: 1, this_city_field: 1 });
	},
	//确认选择
	set_alert_content_confrim: function () {
		var that = this;
		that.setData({ this_city_data: [], select_city_layer_status: false, this_city_parent_level: 1, this_city_field: 1, this_page_size: 1, is_loadmore: true, this_s_keywords: that.data.this_s_keywords, this_user_city: that.data.this_user_select_city });
		wx.setNavigationBarTitle({
			title: that.data.this_app_title + '-' + that.data.this_user_select_city
		});
		that.getIndexData();
	},
	//搜索
	info_search_bind: function (e) {
		this.setData({ this_page_size: 1, is_loadmore: true, this_s_keywords: e.detail.value });
		this.getIndexData();
	},
	//发布信息
	add_info_bind: function () {
		this.setData({ scrollTop: 0 });
		return false;
		wx.switchTab({ url: 'release' });
	},
	//自动定位
	user_location_bind: function () {
		this.getLocation();
	},
	swiperChange: function (e) {
		//this.setData({ swiperCurrent: e.detail.current });
	},
	//广告跳转
	ad_goinfo_bind: function (e) {
		if (e.currentTarget.id && e.currentTarget.id > 0) {
			wx.navigateTo({ url: "detail?id=" + e.currentTarget.id });
		}
	},
	//签到
	go_qiandao_bind:function(){
		wx.navigateTo({ url: "/pages/huodong/qiandao/index"});
	},
	//分享
	go_share_bind:function(){
		wx.navigateTo({ url: "/pages/huodong/fenxiang/index" });
	},
	onLoad: function (op) {
		var that = this;
		that.setData({ this_c_config: app.globalData.app_config_data });
		that.setData({this_config_op: op});
		if (wx.getStorageSync('global_user_address')) {
			that.getSystemConfig();
		} else {
			that.getLocation();
		}
	},
	onShow: function () {
		var that = this;
		if (wx.getStorageSync('index_auto_loading') == 1) {
			that.setData({ this_page_size: 1, is_loadmore: true, this_s_keywords: '' });
			that.getIndexData();
			wx.setStorageSync('index_auto_loading', null);
		}
	},
	getLocation: function () {
		var that = this;
		let qqmapsdk = null;
		_requsetCYZ.cyz_requestGet('/ShopApi/getDailiQQmapKey', {}, function (res) {
			qqmapsdk = new QQMapWX({ key: res.info.mapkey});
			_functionCYZ.CYZ_loading("定位中，请稍候...");
			wx.getLocation({
				type: 'gcj02',
				success: function (res) {
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: res.latitude,
							longitude: res.longitude
						},
						success: (res) => {
							that.setData({ sdk_user_address_info: res.result });
							wx.setStorageSync('global_user_city', res.result.address_component.city);
							wx.setStorageSync('global_user_address', res.result.address);
							wx.setStorageSync('global_user_lat', res.result.location.lat);
							wx.setStorageSync('global_user_lng', res.result.location.lng);
							wx.setStorageSync('global_user_province', res.result.address_component.province);
							wx.setStorageSync('global_user_city', res.result.address_component.city);
							wx.setStorageSync('global_user_district', res.result.address_component.district);
							that.getSystemConfig();
							that.set_alert_content_close();
						}
					});
				},
				fail: function () {
					//弹出系统设置
					wx.openSetting({
						success: (res) => {
							if (res.authSetting['scope.userLocation'] == false) {
								wx.showModal({
									title: '提示',
									content: "请允许地理位置授权",
									showCancel: false,
									success: function () {
										that.getLocation();
									}
								});
							} else {
								that.getLocation();
							}
						}
					});
					return false;
				},
				complete: function () {
					wx.hideLoading();
				}
			})
		})
	},
	//获取系统配置
	getSystemConfig: function () {
		var that = this;
		let op = that.data.this_config_op;
		var requestData = {};
		//添加推广
		requestData.top_user_id = 0;
		if (op.scene != undefined) {
			let scene = decodeURIComponent(op.scene);
			if (op.scene > 0) {
				requestData.top_user_id = scene || 0;
			}
		} else if (op.tg_user_id != undefined){
			if (op.tg_user_id > 0){
				requestData.top_user_id = op.tg_user_id || 0;
			}
		}
		_requsetCYZ.cyz_requestGet('/ShopApi/addFenxiaoUser', requestData, function (cyz_data) {
			wx.hideToast();
			if (cyz_data.code == 1) {
				that.setData({ this_login_user_id: cyz_data.info });
			} else if (cyz_data.code == 2) {
				app.getUserDataToken(function (token) {
					that.getSystemConfig();
				});
				return false;
			}
		});
		//加载系统配置 是否显示评论等功能
		_requsetCYZ.cyz_requestGet('/Index/getConfigOthersValue', {}, function (xyz_data) {
			that.setData({ this_config_commnet_show: xyz_data.info.commnet_is_open, this_app_title: xyz_data.info.app_top_title, this_app_muchcity_open: xyz_data.info.app_muchcity_open, this_huodong_data: xyz_data.info.huodong_data, app_tongji_data: xyz_data.info.app_tongji_data, is_hongbao_open: xyz_data.info.is_hongbao_open, index_isshow_add: xyz_data.info.index_isshow_add, info_index_iconnum:parseInt(xyz_data.info.info_index_iconnum)});
			//如果缓存存在
			var user_city_fanwei = "全国";
			if (wx.getStorageSync('global_user_address')) {
				if (xyz_data.info.app_muchcity_select == 1) {
					user_city_fanwei = wx.getStorageSync("global_user_province");
				} else if (xyz_data.info.app_muchcity_select == 2) {
					user_city_fanwei = wx.getStorageSync("global_user_city");
				} else if (xyz_data.info.app_muchcity_select == 3) {
					user_city_fanwei = wx.getStorageSync("global_user_district");
				}
				that.setData({
					this_user_city: user_city_fanwei,
					this_u_lat: wx.getStorageSync("global_user_lat"),
					this_u_lng: wx.getStorageSync("global_user_lng")
				});
			}else{
				if (xyz_data.info.app_muchcity_select == 1) {
					user_city_fanwei = that.data.sdk_user_address_info.address_component.province;
				} else if (xyz_data.info.app_muchcity_select == 2) {
					user_city_fanwei = that.data.sdk_user_address_info.address_component.city;
				} else if (xyz_data.info.app_muchcity_select == 3) {
					user_city_fanwei = that.data.sdk_user_address_info.address_component.district;
				}
				that.setData({
					this_user_city: user_city_fanwei,
					this_u_lat: that.data.sdk_user_address_info.location.lat,
					this_u_lng: that.data.sdk_user_address_info.location.lng
				});
			}
			if (xyz_data.info.app_muchcity_open) {
				wx.setNavigationBarTitle({
					title: xyz_data.info.app_top_title + '-' + that.data.this_user_city
				});
			} else {
				wx.setNavigationBarTitle({
					title: xyz_data.info.app_top_title
				});
			}
			that.getIndexData();
		});
	},
	getIndexData: function () {
		var that = this;
		_functionCYZ.CYZ_loading();
		//加载首页数据
		var requestData = {};
		requestData.pagesize = that.data.this_page_size;
		requestData.pagenum = that.data.this_page_num;
		requestData.keywords = that.data.this_s_keywords;
		requestData.u_city = that.data.this_user_city;
		requestData.select_type = that.data.select_type;
		requestData.u_lat = that.data.this_u_lat;
		requestData.u_lng = that.data.this_u_lng;
		_requsetCYZ.cyz_requestGet('/Info/getIndexData', requestData, function (xyz_data) {
			wx.hideToast();
			if (xyz_data.code == 2) {
				app.getUserDataToken(function (token) {
					that.getIndexData();
				});
				return false;
			}
			const group = [], styles = {};
			var i = -1;
			let this_next_siwper = that.data.info_index_iconnum *2;
			for (var x in xyz_data.info.cate_list) {
				if (x % this_next_siwper === 0) {
					group[++i] = [];
				}
				const item = xyz_data.info.cate_list[x];
				group[i].push(item);
				try {
					styles[item.id] = JSON.parse(item.style ? item.style : "{}");
				} catch (e) {
					console.error(e);
				}
			}
			if (xyz_data.info.info_list == null) {
				that.setData({ is_loadmore: false });
			} else {
				if (xyz_data.info.info_list.length < that.data.this_page_num) {
					that.setData({ is_loadmore: false });
				}
			}
			that.setData({
				this_cate_list_data: group,
				this_info_list_data: xyz_data.info.info_list,
				this_ad_list_data: xyz_data.info.ad_list,
				swiper_data_num: xyz_data.info.ad_list.length,
				this_one_ad_data: xyz_data.info.ad_one_list,
				this_gonggao_data: xyz_data.info.ad_gonggao_list,
				this_huodong_list: xyz_data.info.index_huodong_list,
				this_service_config: xyz_data.info.app_kefu_config,
				is_show_service: xyz_data.info.app_kefu_config.is_show || false,
				index_share_title:xyz_data.info.index_share_title,
				index_share_img:xyz_data.info.index_share_img
			});
		});

	},



	onReachBottom: function (e) {
		var that = this;
		if (that.data.is_loadmore == false) {
			return false;
		}
		_functionCYZ.CYZ_loading();
		var requestData = {};
		requestData.pagesize = that.data.this_page_size + 1;
		requestData.pagenum = that.data.this_page_num;
		requestData.keywords = that.data.this_s_keywords;
		requestData.u_city = that.data.this_user_city;
		requestData.select_type = that.data.select_type;
		requestData.u_lat = that.data.this_u_lat;
		requestData.u_lng = that.data.this_u_lng;
		_requsetCYZ.cyz_requestGet('/Info/getIndexData', requestData, function (xyz_data) {
			wx.hideToast();
			if (xyz_data.code == 2) {
				app.getUserDataToken(function (token) {
					that.getIndexData();
				});
				return false;
			} else if (xyz_data.code == 1) {
				if (xyz_data.info.info_list == null) {
					that.setData({ is_loadmore: false });
				} else {
					if (xyz_data.info.info_list.length < that.data.this_page_num) {
						that.setData({ is_loadmore: false });
					}
					var this_new_info_data = that.data.this_info_list_data;
					this_new_info_data = this_new_info_data.concat(xyz_data.info.info_list);
					that.setData({ this_info_list_data: this_new_info_data, this_page_size: requestData.pagesize });
				}
			}
		});
	},

	onSwtchTabTap: function (e) {
		var that = this;
		const dataset = e.currentTarget.dataset, index = dataset.index;
		this.setData({ this_page_size: 1, is_loadmore: true, select_type: index });
		if (index == 1) {
			this.setData({ this_show_juli: true });
			if (wx.getStorageSync("global_user_address")) {
				that.getIndexData();
			} else {
				that.getLocation();
			}
		} else {
			this.getIndexData();
			this.setData({ this_show_juli: false });
		}
	},
	/**
	 * 跳转页面
	 */
	onNavigateTap: function (e) {
		const dataset = e.currentTarget.dataset, url = dataset.url, type = dataset.type;
		const nav = { url: url };
		if ("switch" == type) {
			nav.fail = function () {
				wx.navigateTo({ url: url });
			};
			wx.switchTab(nav);
		} else {
			wx.navigateTo(nav);
		}

	},
	/**
	 * 预览视图
	 */
	onPreviewTap: function (e) {
		var dataset = e.target.dataset, index = dataset.index, url = dataset.url;
		if (index === undefined && url === undefined) return;
		var urls = e.currentTarget.dataset.urls;
		urls = urls === undefined ? [] : urls;
		if (index !== undefined && !url) url = urls[index];
		wx.previewImage({ current: url, urls: urls });
	},
	/**
	 * 拨打电话
	 */
	onCallTap: function (e) {
		const dataset = e.currentTarget.dataset, mobile = dataset.mobile;
		wx.makePhoneCall({
			phoneNumber: mobile,
		});
	},
	/**
	 * 赞
	 */
	onGoodTap: function (e) {
		var that = this;
		_functionCYZ.CYZ_loading_n("加载中");
		var requestData = {};
		requestData.info_id = e.currentTarget.dataset.id;
		requestData.action_type = e.currentTarget.dataset.type;
		_requsetCYZ.cyz_requestGet('/InfoAction/goodUpdate', requestData, function (xyz_data) {
			wx.hideLoading();
			if (xyz_data.code == 1) {
				that.getIndexData();
				return true;
			} else if (xyz_data.code == 2) {
				app.getUserDataToken(function (token) {
					that.onGoodTap(e);
				});
				return false;
			} else {
				_functionCYZ.CYZ_alert(xyz_data.info);
				return false;
			}
		});
	},
	/**
	 * 显示评论框
	 */
	onShowCommentTap: function (e) {
		const dataset = e.target.dataset;
		const values = {
			index: e.currentTarget.dataset.index,
			comment_index: dataset.commentIndex,
			reply_id: dataset.replyId,
			reply_uid: dataset.uid,
			doc_id: dataset.docId,
		};
		if (!values.reply_id && !values.doc_id) return;
		const comment_placeholder = (values.reply_id ? "回复 " : "评论 ") + dataset.nickname;
		this.setData({ commentParam: values, show_comment: true, comment_placeholder: comment_placeholder });
	},
	/**
	 * 隐藏评论框
	 */
	onHideCommentTap: function () {
		this.setData({ show_comment: false });
	},
	/**
	 * 提交评论
	 */
	onCommentSubmit: function (e) {
		var that = this;
		_functionCYZ.CYZ_loading_n("请稍候...");
		var requestData = e.detail.value;
		requestData.formId = e.detail.formId;
		requestData.commentParam = that.data.commentParam;
		_requsetCYZ.cyz_requestGet('/InfoAction/commentAdd', requestData, function (xyz_data) {
			wx.hideLoading();
			if (xyz_data.code == 1) {
				that.setData({ show_comment: false });
				wx.navigateTo({ url: 'detail?id=' + xyz_data.info });
				return true;
			} else if (xyz_data.code == 2) {
				app.getUserDataToken(function (token) {
					that.onCommentSubmit(e);
				});
				return false;
			} else {
				_functionCYZ.CYZ_alert(xyz_data.info);
				return false;
			}
		});
	},
	onPullDownRefresh: function () {
		var that = this;
		that.setData({ this_s_keywords: '', this_page_size: 1, is_loadmore: true });
		that.onLoad(that.data.this_config_op);
		setTimeout(() => {
			wx.stopPullDownRefresh()
		}, 1000);
	},
	onShareAppMessage: function () {
		var that = this;
		var shareTitle = that.data.this_app_title;
		var sharePath = 'pages/info/index?tg_user_id=' + that.data.this_login_user_id;
		return {
			title: that.data.index_share_title,
			path: sharePath,
			imageUrl:that.data.index_share_img
		}
	},
})